package com.example.coinhelper.Fragment;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;

import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.coinhelper.Activity.LoginActivity;
import com.example.coinhelper.Activity.MainActivity;
import com.example.coinhelper.Activity.NoteActivity;
import com.example.coinhelper.Bean.Details;
import com.example.coinhelper.Bean.User;
import com.example.coinhelper.Manage.DetailsManage;
import com.example.coinhelper.Manage.UserManager;
import com.example.coinhelper.R;
import com.example.coinhelper.utils.ExportUtil;
import com.example.coinhelper.utils.MySesseion;

import java.io.File;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link MineFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class MineFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private TextView usernameView;
    private TextView lastLoginView;
    private LinearLayout bianqianView;
    private LinearLayout outputView;
    private LinearLayout setPasswordView;
    private LinearLayout zhuxiaoView;

    public MineFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment MineFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static MineFragment newInstance(String param1, String param2) {
        MineFragment fragment = new MineFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_mine, container, false);
        InitView(view);
        // Inflate the layout for this fragment
        return view;
    }
    public void InitView(View view){
        usernameView = view.findViewById(R.id.mine_tv_username);
        lastLoginView = view.findViewById(R.id.fragmentSetting_tv_lastLoginTime);
        usernameView.setText(MySesseion.USER.getUsername());
        lastLoginView.setText(MySesseion.USER.getRegistrationTime());
        bianqianView = view.findViewById(R.id.mine_ll_bianqian);
        outputView = view.findViewById(R.id.output_details);
        setPasswordView = view.findViewById(R.id.setting_ll_setting);
        zhuxiaoView = view.findViewById(R.id.setting_zhuxiao);

        bianqianView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(requireContext(), NoteActivity.class));
                //getActivity().getSupportFragmentManager().beginTransaction().remove(MineFragment.this).commit();

            }
        });
        outputView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DetailsManage detailsManage = new DetailsManage(requireContext());
                List<Details> detailsList = detailsManage.getAllDetailsByUsername(MySesseion.USER.getUsername());
                String filePath = "Details.txt";
                boolean flag = ExportUtil.exportToTxt(requireContext(),detailsList,filePath);
//                File file = new File(filePath);
//                System.out.println("文件路径"+file.getPath());
//                Uri uri = FileProvider.getUriForFile(requireContext(), "com.example.coinhelper.fileprovider", file);

                if(flag){
                    Toast.makeText(requireContext(),"导出成功",Toast.LENGTH_SHORT).show();
//                    Intent intent = new Intent();
//                    intent.setAction(Intent.ACTION_SEND);
//                    intent.setType("text/plain"); // 设置文件类型为纯文本文件 (txt)
//                    intent.putExtra(Intent.EXTRA_STREAM, uri); // 设置文件路径为Uri
//                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//                    startActivity(Intent.createChooser(intent, "对话框标题"));
//                    startActivity(intent); // 启动分享意图
                }else{
                    Toast.makeText(requireContext(),"导出失败",Toast.LENGTH_SHORT).show();
                }
            }
        });
        setPasswordView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
                builder.setTitle("修改密码");

                // 设置布局和视图
                LayoutInflater inflater = LayoutInflater.from(requireContext());
                View view = inflater.inflate(R.layout.change_password_layout, null);
                builder.setView(view);

                // 获取视图中的组件
                EditText newPasswordEditText = view.findViewById(R.id.editTextNewPassword);
                EditText oldPasswordEditText = view.findViewById(R.id.oldPassword);
                EditText confirmPasswordEditText = view.findViewById(R.id.editTextConfirmPassword);
                UserManager userManager = new UserManager(requireContext());



                // 添加确定按钮
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String newPassword = newPasswordEditText.getText().toString();
                        String confirmPassword = confirmPasswordEditText.getText().toString();
                        String oldPassword = oldPasswordEditText.getText().toString();
                        User user = userManager.login(new User(MySesseion.USER.getUsername(),oldPassword));
                        if(user==null){
                            Toast.makeText(requireContext(), "旧密码错误", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        // 在这里处理密码修改逻辑
                        if (newPassword.equals(confirmPassword)) {
                            user.setPassword(newPassword);
                            userManager.updateUserPassword(user);
                            Intent intent = new Intent(requireContext(), LoginActivity.class);
                            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); // 清除当前任务栈并创建新的任务栈
                            startActivity(intent);
                            requireActivity().finish(); // 关闭当前 Activity
                        } else {
                            // 密码不匹配，显示错误信息
                            Toast.makeText(requireContext(), "两次密码不一致", Toast.LENGTH_SHORT).show();
                        }
                    }
                });

                // 添加取消按钮
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });

                // 创建并显示AlertDialog
                AlertDialog alertDialog = builder.create();
                alertDialog.show();
            }
        });
        zhuxiaoView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                androidx.appcompat.app.AlertDialog.Builder builder = new androidx.appcompat.app.AlertDialog.Builder(requireContext());
                builder.setTitle("提示信息").setMessage("您确定要注销账号吗")
                        .setNegativeButton("取消" , null)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                UserManager userManager = new UserManager(requireContext());
                                userManager.deleteUser(MySesseion.USER.getUsername());
                                Toast.makeText(requireContext(), "注销成功", Toast.LENGTH_SHORT).show();
                                Intent intent = new Intent(requireContext(), LoginActivity.class);
                                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); // 清除当前任务栈并创建新的任务栈
                                startActivity(intent);
                                requireActivity().finish(); // 关闭当前 Activity
                            }
                        });
                builder.create().show();
            }
        });

    }

}